package com.imagefake.controller;

import com.alibaba.fastjson2.JSON;
import com.imagefake.entity.PredictedRecord;
import com.imagefake.service.PredictedRecordService;
import com.imagefake.util.QiniuUtil;
import com.imagefake.vo.HttpResult;
import com.imagefake.vo.PredictResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

@RestController
@CrossOrigin
@Slf4j
public class ApiController {
    @Value("${flaskImageFake.url}")
    private String flaskImageFakeUrl;
    private RestTemplate restTemplate = new RestTemplate();

    @Resource
    private PredictedRecordService predictedRecordService;

    @PostMapping("/predict")
    public HttpResult forwardPredict(@RequestParam("file") MultipartFile multipartFile, @RequestParam("userId") Integer userId) {
        try {
            // 创建请求体
            MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
            requestBody.add("file", multipartFile.getResource());

            // 发送POST请求
            String responseJson = restTemplate.postForObject(flaskImageFakeUrl + "/predict", requestBody, String.class);
            PredictResponse predictResponse = JSON.parseObject(responseJson, PredictResponse.class);
            if (predictResponse != null) {
                log.info("请求转发成功：{}", responseJson);
                //未上传用户Id，不进行记录存储，简单转发即可
                if (userId == null) {
                    return new HttpResult(predictResponse.getCode(), predictResponse.getMsg());
                } else {
                    //上传用户Id，进行记录存储
                    //图片检测过程正常
                    if (predictResponse.getCode() == 200) {
                        File file = convertMultiPartToFile(multipartFile);
                        String imageUrl = QiniuUtil.upload(file);
                        if (!imageUrl.isEmpty()) {
                            //存储检测记录
                            PredictedRecord record = new PredictedRecord();
                            record.setUserId(userId);
                            record.setImagePath(imageUrl);
                            record.setCreateTime(new Date());
                            record.setPredictedResult(predictResponse.getMsg());
                            predictedRecordService.save(record);
                            return new HttpResult(200, predictResponse.getMsg());
                        }
                        //图片检测过程报错
                    } else {
                        return new HttpResult(-1, predictResponse.getMsg());
                    }
                }
            } else {
                log.error("请求转发失败");
                return new HttpResult(-1, "请求转发失败");
            }
        } catch (Exception e) {
            // 处理异常情况
            log.error("请求转发失败：{}", e.getMessage());
            return new HttpResult(-1, "请求转发失败");
        }
        return new HttpResult(-1, "请求转发失败");
    }

    private File convertMultiPartToFile(MultipartFile file) throws IOException {
        File convertedFile = new File(file.getOriginalFilename());
        FileOutputStream fos = new FileOutputStream(convertedFile);
        fos.write(file.getBytes());
        fos.close();
        return convertedFile;
    }
}

